#!/bin/sh
# Copyight (C) 2017  www.17ce.com
START=99
CDN_BASE="https://gitee.com/brucelwy/K2_17ce/raw/master/"
UPDATE_URL="https://gitee.com/brucelwy/K2_17ce/raw/master/17ce_version.php"
TEMP_FILE="/tmp/update.txt"
UPDATE_FILE="/tmp/update.tgz"
WORK_DIR="/tmp/17ce"
SAVE_DIR="/etc/storage/17ce"
export LD_LIBRARY_PATH=/lib:$WORK_DIR
logging()
{
    logger -t "【17ce】" "$1"
}
wait_for_network(){
	echo "~~~~~~"
	sleep 2
	echo "~~~~~~"
}
check_update()
{
	wget -T 30 $UPDATE_URL -O  $TEMP_FILE
	TURL=`cat $TEMP_FILE|awk '{print $2}'`
	echo "will download update file -> $TURL"
	wget -T 60 $TURL  -O $UPDATE_FILE
}
wget_install(){
	wget -T 60 -O $1  $2
	chmod +x $1
}
init_files()
{
#       check_update
	killall -9 17ce_v3
	rm -f $WORK_DIR/UUID
	mkdir -p $WORK_DIR
	mkdir -p $SAVE_DIR
	cd $WORK_DIR
	
	if [ ! -f "$WORK_DIR/17ce_v3" ]; then
	
		wget_install 17ce_v3      $CDN_BASE/bin/17ce_v3
		wget_install conf.json    $CDN_BASE/bin/conf.json
		wget_install libgcc_s.so.1   $CDN_BASE/lib/libgcc_s.so.1
		wget_install libcurl.so.4   $CDN_BASE/lib/libcurl.so.4
		wget_install libstdc++.so.6   $CDN_BASE/lib/libstdc.so.6
		wget_install libpolarssl.so.7    $CDN_BASE/lib/libpolarssl.so.7
		wget_install libmbedtls.so.9    $CDN_BASE/lib/libmbedtls.so.9
		wget_install libc.so    $CDN_BASE/lib/libc.so
		wget_install ld-uClibc.so.1    $CDN_BASE/lib/ld-uClibc.so.1
		
		if [ ! -f "/lib/libmbedcrypto.so.0" ]; then
			ln -sf /lib/libmbedcrypto.so $WORK_DIR/libmbedcrypto.so.0
		fi
	fi	
}

start()
{
	echo "begin start 17ce"
	logging "17ce账户："$1""
	wait_for_network
	init_files
	$WORK_DIR/17ce_v3 -u USER_NAME
	echo "17ce Client has stated."
}

stop()
{
	killall -9 17ce_v3
	sleep 1
	echo "17ce Client has stoped."
}

monitor()
{
	if [ "$(date "+%H:%M")" == "00:00" ]; then
		logging "scheduled kill process"
		killall -9 17ce_v3
	fi

	PID=`pidof 17ce_v3`
	echo "pid: $PID"
	if [ "x$PID" = 'x' ]; then
		logging "process die"
		$WORK_DIR/17ce_v3 -u USER_NAME
	fi
}

if [ "$1" = '-m' ]; then
	monitor
else
	start  USER_NAME
fi	
